<?php
/**
 * AWFLogRoute - Ajax Web File Log Route class
 * 
 * This log route is something like a combination of CFileLogRoute and CWebLogRoute.
 * 
 * The main points of this log route is to have valid HTML syntax, clean HTML page and the
 * possibility to get the log for AJAX requests.
 * 
 * The log is saved in a file on the server, this way we have clean HTML page with valid markup.
 * The log is displayed on the web page by using ajax calls that reads the log file.
 * Only the last request is logged as on every new request the log is overwritten, this
 * way we can get just the last request log on the screen.
 * 
 * @author Maurizio Domba <mdomba@gmail.com>
 * @version "0.3" 2012-02-29 15:30 mdomba
 */

class AWFLogRoute extends CLogRoute
{
	/**
	 * @var string directory alias where the log file is stored. Defaults to application runtime path.
	 */
	public $logPath;

	/**
	 * @var string log file name. Defaults to 'awflogroute.log'.
	 */
	public $logFile = 'awflogroute.log';

	/**
	 * @var string directory alias where the AWF Log controller is located. Defaults to 'application.components.AWFLog.AWFLogController'.
	 */
	public $controllerAlias = 'application.components.AWFLog';

	/**
	 * Initializes the route.
	 * This method is invoked after the route is created by the route manager.
	 */
	public function init()
	{
		$options = 'url:"' . Yii::app()->createUrl('AWFLog/index') . '"';
		$request = Yii::app()->getRequest();
		if($request->enableCsrfValidation)
		{
			$options .= ',data:{"' . $request->csrfTokenName . '":"' . $request->csrfToken . '"}';
		}
		$js='(function(){var a,b,c=!1,e=!1,d=$("body");a=$("#AWFLogBtnShow");b=$("#AWFLogBtnHide");0===a.length&&(a=$("<button>",{id:"AWFLogBtnShow",text:"Load Application Log"}),c=!0);0===b.length&&(b=$("<button>",{id:"AWFLogBtnHide",text:"Remove Application Log",css:{display:"none"}}),e=!0);a.on("click",function(){$.ajax({'.$options.',type:"POST",success:function(d){var c=$("#AWFLogData");$.when(c.html(d).slideDown(200)).then(function(){a.text("Re-Load Application Log");b.show();$("html,body").animate({scrollTop:c.offset().top})})}}); return!1});b.on("click",function(){var a=$("#AWFLogData");$.when(a.slideUp(400)).then(function(){a.html("");b.hide()})});c&&e?d.append($("<div>",{id:"AWFLogBtn"}).append(a,b)):(c&&d.append(a),e&&d.append(b));0===$("#AWFLogData").length&&d.append($("<div>",{id:"AWFLogData"}))})();';
/*
// JS code compiled with google closure compiler at http://closure-compiler.appspot.com/home
$js=<<<EOS
(function () {
	var logBtnShow, logBtnHide,
		adShow = false,
		adHide = false,
		page = $('body');
	logBtnShow = $('#AWFLogBtnShow');
	logBtnHide = $('#AWFLogBtnHide');
	if (logBtnShow.length === 0) {
		logBtnShow = $('<button>', {
			id: 'AWFLogBtnShow',
			text: 'Load Application Log'
		});
		adShow = true;
	}
	if (logBtnHide.length === 0) {
		logBtnHide = $('<button>', {
			id: 'AWFLogBtnHide',
			text: 'Remove Application Log',
			css: {
				display: 'none'
			}
		});
		adHide = true;
	}
	logBtnShow.on('click', function () {
		$.ajax({
			$options,
			'type': 'POST',
			'success': function (data) {
				var logData = $('#AWFLogData');
				$.when(logData.html(data).slideDown(200))
					.then(function () {
						logBtnShow.text('Re-Load Application Log');
						logBtnHide.show();
						$('html,body').animate({scrollTop: logData.offset().top});
					});
			}
		});
		return false;
	});
	logBtnHide.on('click', function () {
		var logData = $('#AWFLogData');
		$.when(logData.slideUp(400))
			.then(function () {
				logData.html('');
				logBtnHide.hide();
			});
	});
	if (adShow && adHide) {
		page.append(
			$('<div>', {id: 'AWFLogBtn'}).append(logBtnShow, logBtnHide)
		);
	} else {
		if (adShow) {
			page.append(logBtnShow);
		}
		if (adHide) {
			page.append(logBtnHide);
		}
	}
	if ($('#AWFLogData').length === 0) {
		page.append($('<div>', { id: 'AWFLogData' }));
	}

}());
EOS;
*/
		parent::init();
		if(!$request->getIsAjaxRequest())
		{
			Yii::app()->getClientScript()->registerScript('AWFLogRouteScript', $js, CClientScript::POS_READY);
		}
		Yii::app()->controllerMap['AWFLog'] = $this->controllerAlias . '.AWFLogController';
		if($this->logPath === null)
			$this->logPath = Yii::app()->getRuntimePath();
	}

	/**
	 * Displays the log messages.
	 * @param array $logs list of log messages
	 */
	public function processLogs($logs)
	{
		$this->render('log', $logs);
	}

	/**
	 * Renders the view.
	 * @param string $view the view name (file name without extension). The file is assumed to be located under framework/data/views.
	 * @param array $data data to be passed to the view
	 */
	protected function render($view, $data)
	{
		$app = Yii::app();
		$request = $app->getRequest();

		$r = '<div style="margin:0;padding:5px;background:#666;color:white;border:solid white;border-width:1px 1px 0">';
		$r .= 'Request details:';
		$r .= '<ul style="margin:5px 10px 10px;padding:3px 20px">';
		$r .= '<li>uri: '.$request->getRequestUri().'</li>';
		$r .= '<li>type: '.$request->getRequestType();
		if($request->getIsAjaxRequest())
		{
			$r .= ' - <span style="color:#c3ffaa;font-weight:bold;">AJAX</span>';
		}
		$r .= '</li>';
		$r .= '</ul>';
		$r .= '</div>';

		$viewFile = YII_PATH . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view . '.php';
		ob_start();
		ob_implicit_flush(false);
		include($app->findLocalizedFile($viewFile, 'en'));
		$content = $r . ob_get_clean();

		$logFile = $app->getRuntimePath() . DIRECTORY_SEPARATOR . $this->logFile;
		$fp = @fopen($logFile,'w');
		@flock($fp, LOCK_EX);
		@fwrite($fp, $content);
		@flock($fp, LOCK_UN);
		@fclose($fp);
	}
}